const Koa = require('koa');
const bodyParser = require('koa-bodyparser');
const static = require('koa-static'); // 添加静态资源中间件
const path = require('path'); // 添加路径模块
const { testConnection } = require('./config/db');
const user = require('./routes/userRoutes');
const images = require('./routes/images');
const functions = require('./routes/functions');
const video = require('./routes/videos');
const health = require('./routes/healthtest');
const healtharticle = require('./routes/healtharticle');
const reports = require('./routes/reports');
const reminders = require('./routes/reminders');
const knowledge = require('./routes/knowledge');
const patients = require('./routes/patients');
const clinic = require('./routes/clinic');
const vaccineAppointmentModels = require('./routes/vaccineAppointment');
const vaccine = require('./routes/vaccine');
const vaccineType = require('./routes/vaccineType');
const appointments = require('./routes/appointments');

const app = new Koa();

// 静态资源服务
app.use(static(path.join(__dirname, 'public')));
app.use(static(path.join(__dirname, 'uploads')));

// 中间件
app.use(bodyParser());
// 全局错误处理
app.use(async (ctx, next) => {
  try {
    await next();
  } catch (error) {
    console.error('服务器错误:', error);
    ctx.status = error.status || 500;
    ctx.body = {
      code: ctx.status,
      message: error.message || '服务器内部错误'
    };
  }
});
// 路由
app.use(user.routes()).use(user.allowedMethods());
app.use(images.routes()).use(images.allowedMethods());
app.use(functions.routes()).use(functions.allowedMethods());
app.use(video.routes()).use(video.allowedMethods());
app.use(health.routes()).use(health.allowedMethods());
app.use(healtharticle.routes()).use(healtharticle.allowedMethods());
app.use(reports.routes()).use(reports.allowedMethods());
app.use(reminders.routes()).use(reminders.allowedMethods());
app.use(patients.routes()).use(patients.allowedMethods());
app.use(clinic.routes()).use(clinic.allowedMethods());
app.use(vaccineAppointmentModels.routes()).use(vaccineAppointmentModels.allowedMethods());
app.use(vaccine.routes()).use(vaccine.allowedMethods());
app.use(vaccineType.routes()).use(vaccineType.allowedMethods());
app.use(knowledge.routes()).use(knowledge.allowedMethods());
app.use(appointments.routes()).use(appointments.allowedMethods());
// 启动服务器
const PORT = process.env.PORT || 3000;
async function startServer() {
  // 测试数据库连接
  const isConnected = await testConnection();
  if (!isConnected) {
    console.log('⚠️  服务器将在数据库连接失败的状态下启动，部分功能可能不可用');
  }
  app.listen(PORT, () => {
    console.log(`🚀 服务器启动成功，运行在端口 ${PORT}`);
    console.log(`📊 健康检查地址: http://localhost:${PORT}/api`);
  });
}

// 关闭
process.on('SIGINT', async () => {
  console.log('\n正在关闭服务器...');
  process.exit(0);
});

startServer();

module.exports = app;